﻿#if NET6_0_OR_GREATER
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net;
using System.Text;
using System;
using T.ServiceComponent.Error;
using Microsoft.AspNetCore.Mvc;
using T.ServiceFramework.Spi;

namespace T.SF.Console.HttpHost
{
    public class WebApiExceptionFilterAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 重写基类的异常处理方法
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnException(ExceptionContext actionExecutedContext)
        {
            actionExecutedContext.HttpContext.Response.StatusCode = Convert.ToInt32(HttpStatusCode.InternalServerError);

            var info = new ExceptionInfo();
            info.ErrorInfo = actionExecutedContext.Exception.Message;
            if (actionExecutedContext.Exception is TException)
                info.ErrorCode = (actionExecutedContext.Exception as TException).Code;
            else
                info.ErrorReason = actionExecutedContext.Exception.StackTrace;

            Exception e = actionExecutedContext.Exception;
            if (e != null)
            {
                TSFLogger.Error(e);
            }
            StringBuilder sb = new StringBuilder(100);
            do
            {
                if (e !=null && e.InnerException != null)
                    e = e.InnerException;
                else
                    e = null;

                if (e != null)
                {
                    sb.AppendLine("Inner ErrorInfo:" + e.Message);
                    sb.AppendLine("Inner ErrorReason:" + e.StackTrace);
                }
            }
            while (e != null);
            info.InnerInfo = sb.ToString();



            actionExecutedContext.Result = new JsonResult(info);

            base.OnException(actionExecutedContext);
        }
    }
}
#endif